package com.sxfq.loansupermarket.backsystem.modular.doctorLooked.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.PayServiceInfo;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.service.IDoctorLookedService;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.AddVisitedInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.ConsultantInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.service.IConsultantService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 医生回访
 *
 * @author py
 * @Date 2018年4月19日23:15:54
 */
@Controller
@RequestMapping("/doctorRevisit")
public class DoctorRevisitController extends BaseController {

    @Autowired
    IDoctorLookedService service;

    @Autowired
    IConsultantService consultantService;

    @Autowired
    ICustomerService customerService;

    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/doctorLooked/";


    /**
     * 跳转到医生看诊 传客户ID 和预约ID 和回访时间
     */
    @RequestMapping(value = "/doctor_follow/{ids}")
    public String consultant(@PathVariable String ids,Model model) {
        String id = ids.split(",")[0];
        String reservationsId = ids.split(",")[1];
        String customerId = ids.split(",")[2];
        String revisitTime = ids.split(",")[3];
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ToolUtil.isEmpty(revisitTime)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql1 = "select t2.customer_name as customerName,t2.reservations_id as reservationsId,t2.medical_record_number as medicalRecordNumber,t2.doctor as doctor" +
                ",t2.customer_sex as customerSex,t2.customer_age as customerAge,t2.customer_phone as customerPhone ,t2.field_tc as fieldTc,t2.one_channel as oneChannel,t1.first_visit_date as firstVisitDate" +
                " from " + this.getTableName() + " t2 left join reservations_info t1 on t1.id = t2.reservations_id where t2.id='" + customerId + "'";
        ConsultantInfo consultantInfo = sqlMapper.selectOne(sql1, ConsultantInfo.class);

        String sql2 = "select r.id,r.reservations_id,r.customer_id,r.revisit,r.revisit_time,r.outpatient_name," +
                " r.revisit_content,r.doctor,r.revisit_status,r.remarks  from return_doctor_visit_info r " +
                " where r.customer_id ='"+customerId+"' and r.revisit_time ='"+ revisitTime +"' and id='"+id+"'";
        DoctorRevisitInfo doctorRevisitInfo = sqlMapper.selectOne(sql2, DoctorRevisitInfo.class);

        //随访记录
        String sql4 = "select r.id,r.reservations_id,r.customer_id,r.revisit,r.revisit_time,r.outpatient_name,r.revisit_content,r.doctor,r.revisit_status,r.remarks  from return_doctor_visit_info r where r.customer_id ='"+customerId+"' ";
        List<DoctorRevisitInfo> doctorRevisitInfoList = sqlMapper.selectList(sql4, DoctorRevisitInfo.class);

        for (DoctorRevisitInfo info1 : doctorRevisitInfoList) {
            if (info1.getRevisitTime() != "" && info1.getRevisitTime() != null) {
                info1.setRevisitTime(info1.getRevisitTime().substring(0,11));
            }
        }
        //就诊记录

        String sql5 ="select r.id,r.reservations_id,r.customer_id,r.diagnose_time,r.doctor,r.remarks,r.diagnose_detail,r.pay_service_name,w.field_tc,w.arrival_store,c.diagnose," +
                "c.finnally_time,c.dispose,c.doctor_advice from doctor_diagnosis_info r left join "+ this.getTableName()+" w on w.id =r.customer_id left join case_info c on c.customer_id = w.id" +
                " where r.customer_id ='"+customerId+"' and c.finnally_time = r.diagnose_time ";
        List<DoctorDiagnosisInfo> DoctorDiagnosisInfoList = sqlMapper.selectList(sql5, DoctorDiagnosisInfo.class);
        for (DoctorDiagnosisInfo info1 : DoctorDiagnosisInfoList) {
            if (info1.getDiagnoseTime() != "" && info1.getDiagnoseTime() != null) {
                info1.setDiagnoseTime(info1.getDiagnoseTime().substring(0,11));
            }
        }

        model.addAttribute("consultantInfo", consultantInfo);
        model.addAttribute("doctorRevisitInfoList", doctorRevisitInfoList);  //随访急了
        model.addAttribute("DoctorDiagnosisInfoList", DoctorDiagnosisInfoList); //就诊记录
        model.addAttribute("doctorRevisitInfo", doctorRevisitInfo);
        model.addAttribute("createName",ShiroKit.getUser().getAccount());  //创建人

        return PREFIX + "/doctor_follow.html";
    }

    /**
     * 预约客户管理列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object doctorInfoList(SearchDoctorLookedInfo info, HttpServletRequest request) {
        Page<DoctorLookedInfo> page = new PageFactory<DoctorLookedInfo>().defaultPage();
        try {
            List<DoctorLookedInfo> list = service.selectPageListByDoctorRevisit(page, info);
            page.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    /**
     * 统计查询
     */
    @RequestMapping(value = "/total", method = RequestMethod.GET)
    @ResponseBody
    public List<DoctorLookedInfo> change(String param1) throws Exception {
        String contitionInfo = "";
        if (StringUtils.isNotBlank(param1)) {
            contitionInfo += " and DATE_FORMAT(t.revisit_time, '%Y-%m-%d') = '" + param1 + "' ";
        }
        String sql = "select count(*) as countNum from  return_doctor_visit_info t  where 1=1 " + contitionInfo +

                " union all  select count(*) as countNum from  return_doctor_visit_info t  where t.revisit_status ='1' " + contitionInfo+

                " union all  select count(*) as countNum from  return_doctor_visit_info t  where t.revisit_status ='2' " + contitionInfo;

        List<DoctorLookedInfo> tongJiInfoList1 = sqlMapper.selectList(sql, DoctorLookedInfo.class);
        return tongJiInfoList1;
    }

    /**
     * 医生回访 就诊记录  回访记录
     * @param ids
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/lookDetail/{ids}")
    public String lookDetail(@PathVariable String ids, Model model) throws Exception {
        String reservationsId = ids.split(",")[0];
        String customerId = ids.split(",")[1];
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        //获得客户信息
        String sql = "select * from " + this.getTableName() + "  where id='" + customerId + "'";
        DoctorLookedInfo doctorLookedInfo = sqlMapper.selectOne(sql, DoctorLookedInfo.class);

//        //获得回访记录
//        String sql1 = "select r.doctor,r.reservations_id,r.customer_id,r.revisit,r.revisit_time,r.revisit_content,r.remarks,r.revisit_status,r.outpatient_name from return_doctor_visit_info r where customerId='"+customerId+"' group by r.revisit_time ";
//        DoctorLookedInfo doctorRevisitInfo = sqlMapper.selectOne(sql1, DoctorLookedInfo.class);

        model.addAttribute("doctorLookedInfo", doctorLookedInfo);
//        model.addAttribute("doctorRevisitInfo", doctorRevisitInfo);
        return PREFIX + "doctor_revisit_details.html";
    }

    @RequestMapping(value = "/to_doctor_comment/{id}")
    public String to_doctor_comment(@PathVariable String id, Model model) {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        ConsultantInfo consultantInfo = this.consultantService.selectOneById(id);
        if (consultantInfo != null) {
            if (consultantInfo.getCustomerSex() == 1) {
                consultantInfo.setSex("男");
            } else if (consultantInfo.getCustomerSex() == 2) {
                consultantInfo.setSex("女");
            }
        }
        String sql = "select * from reservations_info where id='" + consultantInfo.getReservationsId() + "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sql, ReservationsInfo.class);
        model.addAttribute("consultantInfo", consultantInfo);
        model.addAttribute("reservationsInfo", reservationsInfo);
        model.addAttribute("reservationsId", consultantInfo.getReservationsId());
        return PREFIX + "doctor_comment.html";
    }

    @RequestMapping(value = "/doctorComment")
    @ResponseBody
    public int doctorComment(@Valid ReservationsInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        return service.doctorComment(info);
    }

    @RequestMapping(value = "/add_isRevisitd")
    @ResponseBody
    public int add_isRevisitd(@Valid CustomerInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String appointmentTime = "";
        if (info.getAppointmentTime() == null || info.getAppointmentTime() == "") {
            appointmentTime = "null";
        } else {
            appointmentTime = "'" + info.getAppointmentTime() + "'";
        }
        if (info.getRevisitContent() == null || info.getRevisitContent() == "") {
            String sql = "update " + this.getTableName() + " set cause_of_no_return_visit='" + info.getCauseOfNoReturnVisit() + "',is_return_visit=" + info.getIsReturnVisit() + "," +
                    "remarks_of_return_visit='" + info.getRemarksOfReturnVisit() + "',reservations='" + info.getReservations() + "',appointment_time=" + appointmentTime + ",return_to_remark='" + ShiroKit.getUser().getAccount() + "'" +
                    " where reservations_id='" + info.getReservationsId() + "'";
            return sqlMapper.update(sql);
        } else {
//            service.updateIsReturnVisit(info);
            consultantService.insertReturnVisit(info);
            String sqlselecthf = "select * from reservations_info a  where a.id='" + info.getReservationsId() + "' limit 0,1";
            ReservationsInfo reservationsInfo = sqlMapper.selectOne(sqlselecthf, ReservationsInfo.class);
            if (reservationsInfo != null) {
                if (reservationsInfo.getHuifang() == null || reservationsInfo.getHuifang() == "") {
                    String updatesql = "update reservations_info a set a.huifang=CONCAT(concat(char(10),' ,<b>" + DateTimeKit.now() + "</b>[" + ShiroKit.getUser().getAccount() + "]:" + info.getRevisitContent() + "'))  where id='" + info.getReservationsId() + "'";
                    sqlMapper.update(updatesql);
                } else {
                    String updatesql = "update reservations_info a set  a.huifang=CONCAT(huifang,concat(char(10),' ,<b>" + DateTimeKit.now() + "</b>[" + ShiroKit.getUser().getAccount() + "]:" + info.getRevisitContent() + "'))  where id='" + info.getReservationsId() + "'";
                    sqlMapper.update(updatesql);
                }
            }
            String sql = "update " + this.getTableName() + " set cause_of_no_return_visit='" + info.getCauseOfNoReturnVisit() + "',is_return_visit=" + info.getIsReturnVisit() + "," +
                    "remarks_of_return_visit='" + info.getRemarksOfReturnVisit() + "',reservations='" + info.getReservations() + "',appointment_time=" + appointmentTime + ",return_to_remark='" + ShiroKit.getUser().getAccount() + "'" +
                    " where reservations_id='" + info.getReservationsId() + "'";
            return sqlMapper.update(sql);
        }
    }

    @RequestMapping(value = "/to_revisitOperation/{reservationsId}")
    public String toRevisitOperation(@PathVariable String reservationsId, Model model) throws Exception {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        List<AddVisitedInfo> revisitRecordList = consultantService.getRevisitRecordList(reservationsId);
        String sql = "select * from reservations_info where id='" + reservationsId + "' limit 0,1";
        model.addAttribute("reservationsId", reservationsId);
        model.addAttribute("revisitRecordList", revisitRecordList);
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sql, ReservationsInfo.class);
        if (reservationsInfo != null) {
            if (reservationsInfo.getCustomerSex() != null) {
                if (reservationsInfo.getCustomerSex() == 1) {
                    reservationsInfo.setSex("男");
                } else {
                    reservationsInfo.setSex("女");
                }
            }
        }
        model.addAttribute("reservationsInfo", reservationsInfo);
        model.addAttribute("reservations", ShiroKit.getUser().getAccount());
        return PREFIX + "is_revisitd.html";
    }


    /**
     * 除单个病例信息(删除按钮ajax 组件请求)
     * 删
     *
     * @param id     病例ID
     * @param result
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/deleteCaseInfo/{id}")
    @ResponseBody
    public int deleteCaseInfo(@PathVariable String id, BindingResult result) throws Exception {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();

        //删除病例对应的牙位信息
        String sql1 = "delete from tooth_site where case_id = '" + id + "'";
        sqlMapper.delete(sql1);

        //删除病例表对应ID的病例信息
        String tableName1 = tableHead + "case_info";
        String sql = "delete from " + tableName1 + " where id = '" + id + "'";

        return sqlMapper.delete(sql);
    }



    public String getTableName() {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "customer_info";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return tableName;
    }

}
